<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use Config;
use Carbon\Carbon;
use App\Http\Controllers\ZHIHU\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuUserPrestige;
use App\Eloqumd\Zhihu\ZhihuFollower;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuAnswer;
use App\Eloqumd\Zhihu\ZhihuAnswerAdopt;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\ZHIHU\Systems\SystemsConfigController as SCC;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuCollection;
use App\Eloqumd\Zhihu\ZhihuFollowerQuestion;
use App\Eloqumd\Zhihu\ZhihuFavouriteQuestion;
use App\Eloqumd\Zhihu\ZhihuVoteAnswer;
use App\Jobs\SystemMessagePublishedNotify;

class PersonalController extends ApiController
{
    private $configSystemPersonal = 'personal';

    // 用户设置
    public function personalSettings(Request $request)
    {
        $param = $request->all();
        // dump($param);exit;
        // 获取可操作数据
        if (is_null($configVal = SCC::getting($this->configSystemPersonal))) {
            return $this->jsonReturns(99999, trans('zhihu.First-Config-Set-Config-Source'), null, 'verror');
        }

        $settings = Arr::only($param, array_keys($configVal));
        $diff = array_diff_key($configVal, $settings);
        if ($diff) {
            $diff = array_fill_keys(array_keys($diff), '');
            $settings = Arr::collapse([$diff, $settings]);
        }

        DB::beginTransaction();
        try {
            $model = ZhihuUser::find($this->apiUser['id']);
            $model->settings = $settings;
            $model->nickname = $param['nickname'] ?? '';
            $model->avatar = $param['avatar'] ?? '';
            $model->save();

            DB::commit();

            // 更新到缓存中
            $redisKey = 'zhihu_' . $this->apiUser['id'] . '_' . $this->apiUser['token'];
            $personalData = unserialize(Redis::get($redisKey));
            $personalData['nickname'] = $param['nickname'];
            $personalData['avatar'] = $param['avatar'];
            $personalData['settings'] = json_encode($settings, 256);
            Redis::setex($redisKey, Redis::ttl($redisKey), serialize($personalData));

            $personalData['settings'] = $settings;
            return $this->jsonReturns(10000, $this->success, $personalData, 'save');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'save');
        }
    }

    // 获取个人信息
    public function getPersonalInfo()
    {
        $redisKey = 'zhihu_' . $this->apiUser['id'] . '_' . $this->apiUser['token'];
        $personalData = unserialize(Redis::get($redisKey));

        // 用户设置数据处理
        if (is_null($personalData['settings']) && !is_null($configVal = SCC::getting($this->configSystemPersonal))) {
            $personalData['settings'] = array_fill_keys(array_keys($configVal), '');
        } else {
            $personalData['settings'] = json_decode($personalData['settings'], true);
        }

        return $this->jsonReturns(10000, $this->success, $personalData, 'get');
    }

    // 获取个人信息通过用户ID
    public function getPersonalInfoByUserId(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $personalData = ZhihuUser::find($userId)->toArray();

        // 用户设置数据处理
        if (is_null($personalData['settings']) && !is_null($configVal = SCC::getting($this->configSystemPersonal))) {
            $personalData['settings'] = array_fill_keys(array_keys($configVal), '');
        } else {
            $personalData['settings'] = !is_array($personalData['settings']) ? json_decode($personalData['settings'], true) : $personalData['settings'];
        }

        $mobile = $personalData['settings']['mobile'] ?? '';
        if ($mobile) {
            $personalData['settings']['mobile'] = hidden_card_str($mobile);
        }
        
        return $this->jsonReturns(10000, $this->success, $personalData, 'get');
    }

    // 用户组件信息
    public function getPersonalComponent(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $key = $request->input('key', '');
        if (!$userId) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        $jsonData = [];
        $user = ZhihuUser::find($userId);
        $jsonData['title'] = $user->nickname;
        $jsonData['img'] = empty($user['avatar']) ? Config::get('api.zhihu_default_img') : $user['avatar'];
        $emptyDesc = trans('zhihu.Empty-User-Desc');
        $jsonData['subtitle'] = is_null($user->settings) ? $emptyDesc : (isset($user->settings['intro']) && !empty($user->settings['intro']) ? $user->settings['intro'] : $emptyDesc);
        $jsonData['color'] = sprintf( "#%06X", mt_rand(0, 0xFFFFFF));

        $list = [];
        $followers = ZhihuFollower::where('follower_id', $userId)->where('status', 1)->count();
        if ($followers) {
            $list[] = ['label' => trans('zhihu.System-Followers'), 'value' => ($followers > 9999 ? (number_format(9999) . '+') : number_format($followers))];
        }
        $fans = ZhihuFollower::where('user_id', $userId)->where('status', 1)->count();
        if ($fans) {
            $list[] = ['label' => trans('zhihu.System-Fans'), 'value' => ($fans > 9999 ? (number_format(9999) . '+') : number_format($fans))];
        }
        $questions = ZhihuQuestion::where('user_id', $userId)->where('status', 1)->count();
        if ($questions) {
            $list[] = ['label' => trans('zhihu.System-Questions'), 'value' => ($questions > 9999 ? (number_format(9999) . '+') : number_format($questions))];
        }
        $comments = ZhihuAnswer::where('user_id', $userId)->where('status', 1)->count();
        if ($comments) {
            $list[] = ['label' => trans('zhihu.System-Comments'), 'value' => ($comments > 9999 ? (number_format(9999) . '+') : number_format($comments))];
        }
        $adopts = ZhihuAnswerAdopt::where('user_id', $userId)->count();
        if ($adopts) {
            $list[] = ['label' => trans('zhihu.System-Adopts'), 'value' => ($adopts > 9999 ? (number_format(9999) . '+') : number_format($adopts))];
        }
        $jsonData['list'] = $list;

        $userComponetBtn = [];
        if ($userId == $this->apiUser['id']) {
            $userComponetBtn['disabled'] = 1;
            $userComponetBtn['follower'] = 0;
        } else {
            $userComponetBtn['disabled'] = 0;
            // 判断是否关注
            $userComponetBtn['follower'] = (int)ZhihuFollower::where('user_id', $userId)->where('follower_id', $this->apiUser['id'])->where('status', 1)->count();
        }

        $finalData['userComponet'] = [$jsonData];
        $finalData['userComponetBtn'] = $userComponetBtn;

        if ($key == 'customer') {
            $prestiges = (int)ZhihuUserPrestige::where('user_id', $userId)->sum('score');
            $rankingsData = ZhihuUserPrestige::groupBy('user_id')->orderby(DB::raw('sum(score)'), 'desc')->pluck('user_id')->toArray();
            $uRank = array_flip($rankingsData)[$userId] ?? '';
            $finalData['customer'] = [
                'prestiges' => ($prestiges < 0 ? 0 : $prestiges),
                'rankings' => empty($rankingsData) ? 0 : ($uRank == '' ? 0 : ($uRank+ 1))
            ];
        }

        return $this->jsonReturns(10000, $this->success, $finalData, 'get');
    }

    // 发送私信
    public function sendPrivateMessage(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $content = $request->input('content', '');
        if (!$userId || !$content) {
            return $this->jsonReturns(99999, trans('zhihu.System-Send-Message-Error'), null, 'verror');
        }

        $msg = new ZhihuMessage;
        $msg->from_id = $this->apiUser['id'];
        $msg->from_name = $this->apiUser['nickname'];
        $msg->to_id = (int)$userId;
        $msg->content = $content;
        $msg->status = 0;
        $msg->is_system = 0;
        $msg->created_at = Carbon::now();
        $msg->save();

        // socket通知
        $job = (new SystemMessagePublishedNotify([
            'channelType' => 'messages',
            'message' => trans('zhihu.System-Message-Content-Simple', ['name' => $this->apiUser['nickname']]),
            'title' => trans('zhihu.System-Private-Message-Notify-Title'),
            'data' => $msg->toArray()
        ]));
        $this->dispatch($job);

        return $this->jsonReturns(10000, trans('zhihu.System-Send-Message-Success'), null, 'message');
    }

    // 声望记录
    public function getListPrestige(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $key = $request->input('key', '');

        $where[] = ['user_id', '=', $this->apiUser['id'], 'AND'];

        $totalCount = ZhihuUserPrestige::where($where)->count();
        $listData = ZhihuUserPrestige::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        if ($key == 'prestige') {
            $prestiges = (int)ZhihuUserPrestige::where('user_id', $this->apiUser['id'])->sum('score');
            $jsonData['prestiges'] = $prestiges < 0 ? 0 : $prestiges;

            $add = (int)ZhihuUserPrestige::where('user_id', $this->apiUser['id'])
                ->where('types', 0)
                ->sum('score');
            $sub = (int)ZhihuUserPrestige::where('user_id', $this->apiUser['id'])
                ->where('types', 1)
                ->sum('score');

            $jsonData['prestigeDetail'] = trans('zhihu.System-Prestiges-Detail', [
                'total' => $prestiges,
                'add' => $add,
                'sub' => 0 - $sub
            ]);
        }

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 获取用户个人中心统计数据
    public function getPersonalTotalNums(Request $request)
    {
        $userId = $request->input('user_id', 0);
        if (!$userId) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        $jsonData = [];

        $blog = (int)ZhihuQuestion::where('cates', 'blog')->where('user_id', $userId)->where('status', 1)->count();
        $jsonData['blog'] = $blog;
        $question = (int)ZhihuQuestion::where('cates', 'question')->where('user_id', $userId)->where('status', 1)->count();
        $jsonData['question'] = $question;
        $link = (int)ZhihuQuestion::where('cates', 'link')->where('user_id', $userId)->where('status', 1)->count();
        $jsonData['link'] = $link;
        $discuss = (int)ZhihuQuestion::where('cates', 'discuss')->where('user_id', $userId)->where('status', 1)->count();
        $jsonData['discuss'] = $discuss;
        $topic = (int)ZhihuQuestion::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['topic'] = $topic;

        $answer = (int)ZhihuAnswer::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['answer'] = $answer;
        $collection = (int)ZhihuCollection::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['collection'] = $collection;
        $followed = (int)ZhihuFollowerQuestion::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['followed'] = $followed;
        $favourited = (int)ZhihuFavouriteQuestion::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['favourited'] = $favourited;
        // $vote = (int)ZhihuVoteAnswer::where('user_id', $userId)->where('status', 1)->count();
        // $jsonData['vote'] = $vote;

        $follower = (int)ZhihuFollower::where('follower_id', $userId)->where('status', 1)->count();
        $jsonData['follower'] = $follower;
        $fance = (int)ZhihuFollower::where('user_id', $userId)->where('status', 1)->count();
        $jsonData['fance'] = $fance;

        return $this->jsonReturns(10000, $this->success, $jsonData, 'get');
    }

    // 修改密码
    public function changePassWord(Request $request)
    {
        $param = $request->all();
        $res = ZhihuUser::changePwd($param, $this->apiUser['id'], $this->apiUser['token']);
        if (!$res['status']) {
            return $this->jsonReturns(50000, $res['message'], null, 'changepwd');
        }

        return $this->jsonReturns(10000, $this->success, null, 'changepwd');
    }
}
